﻿package util.idgenerator;

import java.util.Random;

//长整型ID生成工厂类
public class LongIDGeneratorFactory {
	/**
	 * Long共64位 分布如下： 符号1位 时间42位 统计16位 随机数5位
	 */
	private static final int TIME_SIZE = 42;

	private static final int RANDOM_SIZE = 5;

	private static final int COUNT_SIZE = 16;

	static final long MAX_TIME = 1L << TIME_SIZE;

	static final int MAX_COUNT = 1 << COUNT_SIZE;

	static final int MAX_RANDOM = 1 << RANDOM_SIZE;

	public LongIDGeneratorFactory() {
	}

	private long genLongID() {
		/**
		 * Long共64位 分布如下： 符号 时间 统计 随机数
		 */
		return (getTime() << (COUNT_SIZE + RANDOM_SIZE))
				| (getCount() << RANDOM_SIZE) | getRandom();
	}

	private long getTime() {
		return System.currentTimeMillis() % MAX_TIME;
	}

	private Random random = new Random();

	private int getRandom() {
		return Math.abs(random.nextInt()) % MAX_RANDOM;
	}

	private static int count = 0;

	private static synchronized int getCount() {
		return (count++) % MAX_COUNT;
	}

	public Long generateID() {
		return new Long(genLongID());
	}

	public static void main(String[] args) {
		Long id = (new LongIDGeneratorFactory()).genLongID();
		System.out.println(id + "的长度:" + id.toString().length());
	}

}
